package com.yy.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.io.PrintWriter;

/**
 * des:
 *
 * @author fxiao
 * @date 2020/12/9 13:16
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {



    /**
     * PasswordEncoder是一个专门用于处理加密和解密的接口，这里需要为其指定一个实现类
     *
     * @return
     */
    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(10);
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                //"/login"这个地址可以随意访问
                //其他地址需要登录后访问
                .anyRequest().authenticated()
                .and()
                .addFilterBefore(new JwtFilter(),UsernamePasswordAuthenticationFilter.class)

                //关闭csrf跨域攻击防御
                .csrf().disable()
                //未认证回调
                .exceptionHandling()
                .authenticationEntryPoint((req, resp, exception) -> {
                    resp.setContentType("application/json;charset=utf-8");
                    PrintWriter out = resp.getWriter();
                    out.write(new ObjectMapper().writeValueAsString(exception.getMessage()+"尚未登录，请登录"));
                    out.flush();
                    out.close();
                })

        ;
    }

}
